package com.mxx.common.security;

import com.mxx.common.utils.SignUtil;
import com.mxx.common.utils.Strings;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author itzgyw
 * @Date 2020-02-23
 * @Time 19:11
 * @Description:
 */
public interface ByteChanger {

    default byte[] decode(String text) {
        return this.decode(text, StandardCharsets.UTF_8);
    }

    default byte[] decode(String text, Charset charset) {
        return this.decode(text.getBytes(charset));
    }

    byte[] decode(byte[] bytes);

    default String decodeToString(String text) {
        return this.decodeToString(text, StandardCharsets.UTF_8);
    }

    default String decodeToString(String text, Charset charset) {
        return this.decodeToString(text.getBytes(charset), charset);
    }


    default String decodeToString(byte[] bytes) {
        return decodeToString(bytes, StandardCharsets.UTF_8);
    }

    default String decodeToString(byte[] bytes, Charset charset) {
        byte[] resBytes = decode(bytes);
        return new String(resBytes, charset);
    }

    default byte[] encode(String text) {
        return encode(text, StandardCharsets.UTF_8);
    }

    default byte[] encode(String text, Charset charset) {
        return encode(text.getBytes(charset));
    }

    byte[] encode(byte[] bytes);

    default String encodeToString(String text) {
        return encodeToString(text, StandardCharsets.UTF_8);
    }

    default String encodeToString(String text, Charset charset) {
        return encodeToString(text.getBytes(charset), charset);
    }


    default String encodeToString(byte[] bytes) {
        return encodeToString(bytes, StandardCharsets.UTF_8);
    }

    default String encodeToString(byte[] bytes, Charset charset) {
        byte[] resBytes = this.encode(bytes);
        return new String(resBytes, charset);
    }

    static ByteChanger base64ByteChanger() {
        return Base64ByteChanger.CHANGER;
    }

    static ByteChanger hexByteChanger() {
        return HexByteChanger.CHANGER;
    }

    class Base64ByteChanger implements ByteChanger {
        private static final Base64ByteChanger CHANGER = new Base64ByteChanger();

        @Override
        public byte[] decode(byte[] bytes) {
            return Base64.getDecoder().decode(bytes);
        }

        @Override
        public byte[] encode(byte[] bytes) {
            return Base64.getEncoder().encode(bytes);
        }
    }

    class HexByteChanger implements ByteChanger {
        private static final HexByteChanger CHANGER = new HexByteChanger();


        @Override
        public byte[] encode(byte[] bytes) {
            return SignUtil.byteToHex(bytes).getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public byte[] decode(byte[] bytes) {
            return SignUtil.hexToByte(Strings.toString(bytes));
        }


    }
}
